package com.work.servlet.student;

import com.work.bean.Student;
import com.work.service.MyClassService;
import com.work.service.UserService;
import com.work.service.impl.MyClassServiceImpl;
import com.work.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Administrator on 2017/10/12.
 */
@WebServlet("/stu_add_class")
public class StuAddClassServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        doPost(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();

        if (session.getAttribute("isLogin") != null && (Boolean) session.getAttribute("isLogin")) {

            int studentId = Integer.parseInt(String.valueOf(session.getAttribute("studentId")));
            int classId = Integer.parseInt(req.getParameter("classid"));

            resp.setCharacterEncoding("utf-8");

            MyClassService myClassService = new MyClassServiceImpl();

            if (myClassService.findById(classId).size() == 0){

                resp.getWriter().write("<script>alert('不存在的班级，请重新输入');window.location='student_my_class.jsp'</script>");

            }else {

                UserService service = new UserServiceImpl();
                service.updateStudentClassId(new Student(studentId, classId));

                resp.getWriter().write("<script>alert('成功加入班级');window.location='stu_my_class'</script>");
            }


        } else {
            session.setAttribute("error", "请登录后访问");
            resp.sendRedirect("login.jsp");
        }

    }
}
